package com.opencv.thread;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import org.apache.poi.ss.formula.functions.T;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;

/**
 * @author qz.wu
 * @date 2022/1/20 14:29
 * @descriptions TODO
 */
public class LiteTask {

    /**
     * 异步批量执行任务提交
     *
     * @param jobData
     * @param partShardSize
     * @param task
     * @param <T>
     */
    public static <T> void executeAsyncTask(List<T> jobData, int partShardSize, AsyncTask task) {
        if (CollectionUtil.isEmpty(jobData)) {
            return;
        }
        List<List<T>> partitionList = Lists.partition(jobData, partShardSize);
        AtomicReference<Integer> i = new AtomicReference<>(1);
        partitionList.stream().forEach(partShard -> {
            System.out.println("第" + i + "批异步任务数据") ;
            ThreadPool.executeAsyncTask(() -> task.run(partShard));
            i.set(i.get() + 1);
        });
    }

    /**
     * 同步批量执行任务提交
     *
     * @param jobData
     * @param partShardSize
     * @param func
     * @param <T>
     * @param <R>
     * @return
     */
    public static <T, R> List<R> executeSyncTask(List<T> jobData, int partShardSize, Function<List<T>, List<R>> func) {
        if (CollectionUtil.isEmpty(jobData)) {
            return Collections.EMPTY_LIST;
        }

        List<List<T>> partitionList = Lists.partition(jobData, partShardSize);
        List<R> resultList = Lists.newArrayList();
        partitionList.stream().forEach(partShard -> {
            List<R> apply = func.apply(partShard);
            if (CollectionUtil.isNotEmpty(apply)) {
                resultList.addAll(apply);
            }
        });

        return resultList;
    }

    /**
     * 提交同步任务
     *
     * @param callable
     * @return
     * @throws Exception
     */
    public static Boolean submitSyncTask(Callable<T> callable) throws Exception {
        try {
            ThreadPool.submitSyncTask(callable);
        } catch (Exception ex) {
            throw ex;
        }
        return Boolean.TRUE;
    }

    /**
     * 执行同步任务
     *
     * @param common
     * @return
     * @throws Exception
     */
    public static Boolean executeSyncTask(Runnable common) throws Exception {
        try {
            ThreadPool.executeSyncTask(common);
        } catch (Exception ex) {
            throw ex;
        }
        return Boolean.TRUE;
    }

    /**
     * 执行异步任务
     *
     * @param common
     */
    public void executeAsyncTask(Runnable common) {
        ThreadPool.executeAsyncTask(common);
    }
}
